<template>
  <div class="main-app">
    <el-row style="margin-top: 10px">
      <el-form ref="form" :model="form" :rules="rules" style="width: 50%;margin-left: 25%;">

        <el-form-item label="虚拟卡号:" required prop="virtualCard">
          <el-input v-model="form.virtualCard" />
        </el-form-item>
        <el-form-item label="姓名:" required prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="手机:" required prop="phone">
          <el-input v-model="form.phone" />
        </el-form-item>
        <el-form-item label="组信息:">
          <el-select v-model="form.groupId" placeholder="请选择所属组" style="width: 100%;" @change="ChangeGroup">
            <el-option v-for="item in groupList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="角色:">
          <el-select multiple v-model="selectedRoleList" placeholder="请选择" style="width: 100%;">
            <el-option-group v-for="group in rolesOptions" :key="group.seriesType" :label="group.seriesName"
              style="color: red; font-size: 15px;">
              <el-option v-for="item in group.options" :key="item.id" :label="item.name+'【'+group.seriesName+'】'"
                :value="item.id">
                <span style="float: left;">{{ item.name }}</span>
                <!-- <span style="float: right; color: #8492a6; font-size: 13px; margin-right: 20px;">{{ item.id }}</span> -->
              </el-option>

            </el-option-group>
          </el-select>
        </el-form-item>

        <el-form-item label="性别:" required>
          <el-radio-group v-model="form.sex">
            <el-radio :label="0">男</el-radio>
            <el-radio :label="1">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="是否在职:" required>
          <el-radio-group v-model="form.disabled">
            <el-radio :label="0">在职</el-radio>
            <el-radio :label="1">离职</el-radio>
          </el-radio-group>
        </el-form-item>



      </el-form>
    </el-row>

    <el-row style="margin-top: 40px; text-align: center">
      <el-form :inline="true" class="form-inline">
        <el-form-item>
          <el-button type="primary" :loading="isLoading" @click="save">保存</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-row>
  </div>
</template>

<script>
  import {
    addUsers,
    getUserInfoById
  } from '../../api/user.js';
  import {
    GetAllRolesAsync
  } from '../../api/role.js';
  import {
    GroupAllLists,
    GetUserRoleListAsync,
    GroupAppSeriesByAllRoleLists
  } from '../../api/group.js';
  import {
    createCode
  } from '../../utils/index.js'

  export default {
    data() {
      return {
        isLoading: false,
        id: "",
        Guid: "",
        rolesOptions: [],

        allRoleList: [],
        selectedRoleList: [],

        tableData: [],
        number: 0,
        weight: 0,
        form: {
          sex: 0,
          disabled: 0,
          virtualCard:""
        },
        roleList: [], //所有角色数组
        groupList: [],
        rules: {
          name: [{
            required: true,
            message: "请输入用户姓名",
            trigger: "blur"
          }],
          virtualCard: [{
            required: true,
            message: "请输入虚拟卡号",
            trigger: "blur"
          }],
          phone: [{
            required: true,
            message: "请输入手机号",
            trigger: "blur"
          }],
          groupId: [{
            required: true,
            message: "请选择组信息",
            trigger: "change"
          }],
          role: [{
            required: true,
            message: "请选择角色",
            trigger: "change"
          }],

        },
      };
    },
    watch: {
      selectedRoleList(newName, oldName) {
        let _this = this;
        // 说明新增选项了
        if (newName.length >= oldName.length) {
          // 获取老数组中所有角色的系列
          let roleObjList = [];
          oldName.forEach(item => {
            let index = _this.allRoleList.findIndex(T => {
              return T.id === item;
            })
            if (index >= 0) {
              roleObjList.push(_this.allRoleList[index])
            }
          })
          // console.log("老数据已选择的角色obj:", roleObjList);


          newName.forEach(item => {
            let index = oldName.findIndex(T => {
              return T === item;
            })

            let currentObj = {};
            if (oldName.length == 0) {

              currentObj = _this.allRoleList.find(T => {
                return T.id === newName[0]
              });
            } else {
              if (index < 0) {

                currentObj = _this.allRoleList.find(T => {
                  return T.id === item
                });

              }
            }

            for (let i = 0; i < roleObjList.length; i++) {

              if (roleObjList[i].seriesType === currentObj.seriesType) {
                // console.log("相同的系列：",roleObjList[i].seriesType);
                let index2 = _this.selectedRoleList.findIndex(M => {
                  return M === roleObjList[i].id
                })
                // console.log('index2', index2);
                if (index2 >= 0) {
                  _this.selectedRoleList.splice(index2, 1)
                }
              }
            }

          })
        } else {
          //说明取消选项了

        }

      }
    },

    async created() {
           this.form.virtualCard = createCode(10).toString();
      const {
        userid,
        id
      } = this.$route.params;
      this.Guid = userid;

      // 组织id
      this.id = id;
      // await this.GetUserRoleListAsync(Guid);
      // 获取全部组信息
      await this.GroupAllLists();
      await this.getUserInfoById(userid);



    },

    methods: {

      async ChangeGroup(opt) {
        var parmas = {
          GroupId: opt,
          OrgGuid: this.id
        }
        // 获取组下面全部角色信息
        const {
          data
        } = await GroupAppSeriesByAllRoleLists(parmas)

        if (data) {
          this.form.groupId = opt;
          this.allRoleList = data; //基础的全部角色信息
          this.allRoleList.forEach(item => {
            item.id = item.id.toString();
          })

        }
        this.selectedRoleList = [];

        this.rolesOptions = []; //多选框中的选项数据
        this.allRoleList.forEach(item => {
          if (this.rolesOptions.length != 0) {

            //判断当前角色所属产品系列是否已经存在
            let index = this.rolesOptions.findIndex(T => {
              return T.seriesType == item.seriesType
            })
            if (index >= 0) {
              let roleObj = {
                id: item.id,
                name: item.name,
                seriesName: item.seriesName,
              }
              this.rolesOptions[index].options.push(roleObj);
            } else {
              let roleOptionObj = {
                seriesType: item.seriesType,
                seriesName: item.seriesName,
                options: [{
                  id: item.id,
                  name: item.name,
                  seriesName: item.seriesName,
                }]
              }
              this.rolesOptions.push(roleOptionObj);
            }
          } else {

            let roleOptionObj = {
              seriesType: item.seriesType,
              seriesName: item.seriesName,
              options: [{
                id: item.id,
                name: item.name,
                seriesName: item.seriesName,
              }]
            }
            // let roleObj = {
            //   id: item.id,
            //   name: item.name,
            //   seriesName: item.seriesName
            // }

            this.rolesOptions.push(roleOptionObj);
          }

        })
        if (this.rolesOptions.length > 0 && this.rolesOptions[0].options.length > 0) {
          this.selectedRoleList.push(this.rolesOptions[0].options[0].id)
        }


      },

      async GroupAllLists() {
        const {
          data
        } = await GroupAllLists({
          "OrgGuid": this.id,
        });

        if (data) {

          this.groupList = data;
        }
      },



      async getUserInfoById(Guid) {
        const {
          data,
          data2
        } = await getUserInfoById(Guid);
        if (data) {
          // 存在用户数据
          data.sex = parseInt(data.sex);
          if (data.sex !== 1) {
            data.sex = 0
          }

          data.status = parseInt(data.status);
          data.roleId = parseInt(data.roleId);
          this.form = data;
          await this.ChangeGroup(this.form.groupId);
          if (data2) {
            this.selectedRoleList = data2.map(res => {
              return res.roleId
            })
          }
        } else {
          // 说明是新增用户

          if (this.groupList.length != 0) {
            await this.ChangeGroup(this.groupList[0].id);
          } else {
            console.log("无组数据");
          }
        }
      },

      save() {
        // 校验必填项
        this.$refs["form"].validate(async (valid) => {

          if (valid) { // 校验成功

            let data = {};
            let role = [];

            if (this.selectedRoleList.length === 0) {
              this.$notify.error('请选择角色信息！')
              return
            }
            if (this.form.groupId === '') {
              this.$notify.error('请选择组信息！')
              return
            }
            this.isLoading = true;
            this.selectedRoleList.forEach(item => {
              let index = this.allRoleList.findIndex(T => {
                return T.id === item
              })
              if (index >= 0) {
                role.push(this.allRoleList[index]);
              }
            })
            let roleStr = '';
            if (role.length >= 0) {
              roleStr = JSON.stringify(role)
            }
            let group = this.groupList.find(item => {
              return item.id === this.form.groupId
            })

            let message = "";
            if (this.Guid) {

              data = {
                Name: this.form.name,
                Guid: this.Guid,
                Sex: this.form.sex.toString(),
                Phone: this.form.phone,
                VirtualCard: this.form.virtualCard,
                Disabled: this.form.disabled,
                "OrgRemarks": "",
                "GroupId": this.form.groupId,
                "GroupName": group.name,
                "UserRoles": roleStr,
                "OrgGuid": this.id, //如果不传此ID，则默认添加到登陆人所属组织下

              };
              message = "用户修改成功";


            } else {
              data = {
                Name: this.form.name,
                Sex: this.form.sex.toString(),
                Phone: this.form.phone,

                VirtualCard: this.form.virtualCard,
                Disabled: this.form.disabled,
                "OrgGuid": this.id, //如果不传此ID，则默认添加到登陆人所属组织下
                "OrgRemarks": "",

                "GroupId": this.form.groupId,
                "GroupName": group.name,
                "UserRoles": roleStr,
              };

              message = "用户新增成功";
            }

            const {
              success,
              msg
            } = await addUsers(data);
            this.isLoading = false;
            if (success) {
              this.$notify({
                title: "成功",
                message: message,
                type: "success",
                duration: 3000,
              });
              this.cancel();
            } else {
              this.$notify({
                title: "失败",
                message: msg,
                type: "fail",
                duration: 3000,
              });
            }


          }
        });
      },

      cancel() {
        this.$emit("cancel");
      },
    },
  };
</script>
